package com.heima.behavior.service.impl;

import com.heima.behavior.dto.UnLikesBehaviorDto;
import com.heima.behavior.entity.ApUnlikesBehavior;
import com.heima.behavior.service.IUnLikesBehaviorService;
import com.heima.common.dto.ResponseResult;
import com.heima.common.dto.User;
import com.heima.common.util.AppThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class UnLikesBehaviorServiceImpl implements IUnLikesBehaviorService {

    @Autowired
    MongoTemplate mongoTemplate;

    @Override
    public ResponseResult unLike(UnLikesBehaviorDto dto) {
        //构建ApUnlikesBehavior
        ApUnlikesBehavior unlikesBehavior = new ApUnlikesBehavior();
        unlikesBehavior.setArticleId(dto.getArticleId());
        unlikesBehavior.setType(dto.getType());
        unlikesBehavior.setCreatedTime(new Date());
        Query query = new Query();
        query.addCriteria(Criteria.where("articleId").is(dto.getArticleId()));
        //判断用户登录
        User user = AppThreadLocalUtil.get();
        if (user != null) {
            unlikesBehavior.setUserId(user.getUserId());
            query.addCriteria(Criteria.where("userId").is(user.getUserId()));
        } else {
            unlikesBehavior.setEquipmentId(dto.getEquipmentId());
            query.addCriteria(Criteria.where("equipmentId").is(dto.getEquipmentId()));
        }
        //查询历史记录
        ApUnlikesBehavior one = mongoTemplate.findOne(query, ApUnlikesBehavior.class);
        if (one == null) {
            if (dto.getType() == 0) {
                mongoTemplate.save(unlikesBehavior);
            }
        } else {
            if (one.getType() != dto.getType()) {
                one.setType(dto.getType());
                mongoTemplate.save(one);
            }
        }
        return ResponseResult.okResult();
    }

    //查询不喜欢
    @Override
    public ResponseResult<ApUnlikesBehavior> getUnLikes(UnLikesBehaviorDto dto) {
        Query query = new Query();
        query.addCriteria(Criteria.where("articleId").is(dto.getArticleId()));
        if (dto.getUserId() != null) {
            query.addCriteria(Criteria.where("userId").is(dto.getUserId()));
        } else {
            query.addCriteria(Criteria.where("equipmentId").is(dto.getEquipmentId()));
        }
        query.addCriteria(Criteria.where("type").is(0));
        //查询是否有记录
        ApUnlikesBehavior one = mongoTemplate.findOne(query, ApUnlikesBehavior.class);
        return ResponseResult.okResult(one);
    }
}
